package com.artqiyi.dollmachine.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class NetworkUtil {

	/**
	 * 判断网络是否已连接
	 */
	public static boolean isConnected(Context context) {

		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		if(null != connectivity) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if(null != info && info.isConnected()) {
				if(info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	public static String getLocalIpAddress() {
		return getIpAddress();
//		return getWifiIpAddress(context);
	}

	public static String getIpAddress() {
		try {
			for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
				NetworkInterface net = en.nextElement();
				for(Enumeration<InetAddress> enumIpAddr = net.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
						String ip = inetAddress.getHostAddress();
						Log.d(NetworkUtil.class.getSimpleName(), ip);
						return ip;
					}
				}
			}
		} catch(SocketException ex) {
			Log.e(NetworkUtil.class.getSimpleName(), ex.toString());
		}
		return "";
	}

	private static String intToIp(int i) {

		return (i & 0xFF) + "." +
				((i >> 8) & 0xFF) + "." +
				((i >> 16) & 0xFF) + "." +
				(i >> 24 & 0xFF);
	}
}
